package bank;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GetMoney extends JPanel implements ActionListener {
    private Atm frame;
    private Icon btnOff = Util.getIcon("/images/buttonOff.jpg");
    private Icon btnSure = Util.getIcon("/images/buttonSure.jpg");
    private JButton imageBtn2 = new JButton(btnSure);
    private JButton imageBtn1 = new JButton(btnOff);
    private JTextField getText = new JTextField();

    public GetMoney(Atm frame) {
        this.frame = frame;
        this.setLayout(null);
        this.setOpaque(false);
        JLabel save = new JLabel("取钱");
        save.setBounds(50, 50, 100, 50);
        this.add(save);

        JLabel acc = new JLabel("请输入存款金额:");
        acc.setFont(new Font("宋体", Font.PLAIN, 20));
        acc.setBounds(200, 200, 300, 50);
        this.add(acc);


        getText.setBounds(400, 200, 300, 50);
        getText.setFont(new Font("宋体", Font.PLAIN, 20));
        this.add(getText);


        imageBtn1.setBounds(650, 430, 140, 50);
        this.add(imageBtn1);
        imageBtn1.addActionListener(this);
        imageBtn2.setBounds(300, 430, 140, 50);
        this.add(imageBtn2);
        imageBtn2.addActionListener(this);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == imageBtn1) {
            frame.switchPanel("menu");
        } else if (e.getSource() == imageBtn2) {
            if (!getText.getText().matches("^[0-9]+(.[0-9]{1,2})?$")){
                JOptionPane.showMessageDialog(this, "错误代码");
                return;
            }
            Double m = Double.parseDouble(getText.getText());
            if (m <= frame.getUsers().get(frame.getIndex()).getBalance()) {
                frame.getUsers().get(frame.getIndex()).setBalance(frame.getUsers().get(frame.getIndex()).getBalance() - m);
               String sql="UPDATE t_users SET u_money="+frame.getUsers().get(frame.getIndex()).getBalance()+" where u_name='"+frame.getUsers().get(frame.getIndex()).getAccount()+"'";
               Util.insert(sql);
                JOptionPane.showMessageDialog(this, "取款成功");
                getText.setText("");
            } else {
                JOptionPane.showMessageDialog(this, "账户余额不足");
                getText.setText("");
            }
        }
    }
}
